/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: HuaTiFaBuActivity.java
 * @Package com.jiyi.activity.main
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-6-26 上午10:53:39
 * @version V1.0
 */
package com.jiyi.activity.main;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.SinglePicSourceActivity;
import com.jiyi.bean.main.TopicCatBean;
import com.jiyi.bean.zone.RObject;
import com.jiyi.bean.zone.Topic;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.TopicListEvent;
import com.jiyi.inteface.TopicRemoveInteface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.AutoLinefeedLayout;
import com.jiyi.widget.REditText;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: HuaTiFaBuActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-26 上午10:53:39
 *
 */
public class HuaTiFaBuActivity extends SinglePicSourceActivity implements
        TopicRemoveInteface {

    /* 头部 */
    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;

    @BindView(R.id.gvPic)
    GridView gvPic;
    @BindView(R.id.llHuaTi)
    AutoLinefeedLayout llHuaTi;
    @BindView(R.id.etContent)
    REditText etContent;

    TopicCatBean mTopicCatBean;
    List<TopicCatBean> huaTiTypeDatas = new ArrayList<TopicCatBean>();
    LayoutInflater inflater;
    List<RObject> topicDatas = new ArrayList<RObject>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huati_fabu);
        ButterKnife.bind(this);
        inflater = LayoutInflater.from(this);
        etContent.setTopicRemoveInteface(this);
        getIntentData();
        setTop();
        getTopicCatData();
        fillHuaTiData();
        setMax(3);
        refreshAdapter(gvPic);
    }

    /**
     * @author: HYM
     * @Title: getTopicCatData
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-7-22
     */
    private void getTopicCatData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

        dialog = showDialog(dialog);
        VolleyRequest.StringRequestPost(getContext(),
                WebApi.MAIN_TOPIC_CAT_LIST, "", params, new StringInterface(
                        getContext()) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                String data = obj.getString("data");
                                JSONObject dataJson = new JSONObject(data);
                                String topicJson = dataJson
                                        .getString("topic_act");
                                List<TopicCatBean> temp = new Gson().fromJson(
                                        topicJson,
                                        new TypeToken<List<TopicCatBean>>() {
                                        }.getType());
                                huaTiTypeDatas.clear();
                                huaTiTypeDatas.addAll(temp);
                                fillHuaTiData();
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                            hideDialog(dialog);
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        hideDialog(dialog);
                        ToastUtil.getInstances().showMsg(R.string.err_http_response);
                    }
                });
    }

    /**
     * @author: HYM
     * @Title: fillHuaTiData
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-6-26
     */
    private void fillHuaTiData() {
        llHuaTi.removeAllViews();
        for (int i = 0; i < huaTiTypeDatas.size(); i++) {
            final TopicCatBean mainHuaTiBean = huaTiTypeDatas.get(i);
            View item = inflater.inflate(R.layout.item_huati_type, null, false);
            CheckBox cbType = (CheckBox) item.findViewById(R.id.cbType);
            cbType.setText("#" + mainHuaTiBean.getName() + "#");
            cbType.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                                             boolean isChecked) {
                    if (isChecked) {
                        // 选中插入话题的编辑框
                        setTopic(mainHuaTiBean);
                    } else {
                        // 不选中移除话题出编辑框
                        removeTopic(mainHuaTiBean);
                    }
                }
            });
            // 这边做个判断，如果是当前的话题就默认选中
            if (mainHuaTiBean.getName().equals(this.mTopicCatBean.getName())) {
                cbType.setChecked(true);
                cbType.setEnabled(false);
            }
            llHuaTi.addView(item);
        }
    }

    /**
     * @author: HYM
     * @Title: setHuaTiAdapter
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-6-26
     */
    // private void setHuaTiAdapter() {
    // mCommonAdapter = new CommonAdapter<TopicCatBean>(this, huaTiTypeDatas,
    // R.layout.item_huati_type) {
    //
    // @Override
    // public void convert(ViewHolder holder, TopicCatBean t) {
    // holder.setCheckBoxText(R.id.cbType, t.getName());
    // }
    // };
    // gvHuaTi.setAdapter(mCommonAdapter);
    // }
    private void getIntentData() {
        mTopicCatBean = new Gson().fromJson(
                getIntent().getStringExtra("topicCatBean"), TopicCatBean.class);
    }

    private void setTop() {
        tvBack.setText("");
        tvTitle.setText(mTopicCatBean.getName());
        tvSearch.setCompoundDrawables(null, null, null, null);
        tvSearch.setText("发布");
    }

    @OnClick({R.id.tvBack, R.id.tvSearch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvBack:
                finish();
                break;
            case R.id.tvSearch:
                // 发布
                doPost();
                break;
            default:
                break;
        }
    }

    /**
     * 添加设置话题
     *
     * @author Ruffian
     */
    private void setTopic(TopicCatBean mht) {

        Topic topic = new Topic();
        topic.setId(mht.getId());
        topic.setObjectText(mht.getName());// 必须设置
        // 设置当前选择的话题不可以删除
        if (mht.getId().equals(mTopicCatBean.getId())) {
            topic.setCanDel(false);
        }
        etContent.setObject(topic);// 设置话题
    }

    /**
     * @author: HYM
     * @Title: removeTopic
     * @Description: TODO(从底部按钮删除话题)
     * @param mht
     *            void
     * @date: 2017-6-27
     */
    private void removeTopic(TopicCatBean mht) {
        for (int i = 0; i < etContent.getObjectsNoClear().size(); i++) {
            Topic topic = (Topic) etContent.getObjectsNoClear().get(i);
            if (topic.getId().equals(mht.getId())) {
                etContent.removeObject(topic);
            }
        }
    }

    private String getTopicsIds() {

        /**
         * 获取话题对象集合,遍历
         */
        topicDatas = etContent.getObjects();// 获取话题对象集合
        if (topicDatas == null || topicDatas.size() == 0) {
            return "";
        }

        Topic topic;
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < topicDatas.size(); i++) {
            topic = (Topic) topicDatas.get(i);// 强制转化为开发者topic类型
            stringBuffer.append(topic.getId());
            stringBuffer.append(",");
        }

        Log.e("输出话题对象	", stringBuffer.toString());

        String result = stringBuffer.toString();
        if (result.endsWith(",")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * <p>
     * Title: onRemove
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param id
     * @see TopicRemoveInteface#onRemove(String)
     */
    @Override
    public void onRemove(String id) {
        for (int i = 0; i < huaTiTypeDatas.size(); i++) {
            TopicCatBean mainHuaTiBean = huaTiTypeDatas.get(i);
            if (mainHuaTiBean.getId().equals(id)) {
                View view = llHuaTi.getChildAt(i);
                CheckBox cbType = (CheckBox) view.findViewById(R.id.cbType);
                cbType.setChecked(false);
                break;
            }
        }

    }


    Context getContext() {
        return this;
    }



    void doPost() {
        String webApi = WebApi.MAIN_TOPIC_FABU;

        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
        // 类别id (以字符串的形式逗号隔开，)
        params.put("catIds", getTopicsIds());
        params.put("content", etContent.getText().toString());

        PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
        postForm.params(params);
        // 图片数组
        int size = PicSelectConstans.publish_pics.size();
        File file;
        for (int i = 0; i < size; i++) {
            file = new File(PicSelectConstans.publish_pics.get(i));
            postForm.addFile("image[]", "pic" + (i + 1) + ".jpg", file);
        }

        dialog = showDialog(dialog);
        postForm.build().execute(new StringCallback() {

            @Override
            public void onError(Call arg0, Exception exception, int arg2) {
                hideDialog(dialog);
                ToastUtil.getInstances().showMsg(exception.getMessage());
            }

            @Override
            public void onResponse(String result, int arg1) {
                try {
                    JSONObject obj = new JSONObject(result);
                    String status = obj.getString("status");
                    String info = obj.getString("info");
                    if (status.equals("200")) {
                        EventBus.getDefault().post(new TopicListEvent(TopicListEvent.MAIN_TOPIC_FRAGMENT));
                        finish();
                    } else if (status.equals("404") && info.contains("尚未登录")) {
                        ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
                        //清除环信登录
                        UserHelp.getInstance().clearUser(AppBase.Context, true);
                        return;
                    } else {
                        ToastUtil.getInstances().showMsg(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    hideDialog(dialog);
                }
            }
        });
    }
}
